package main

import (
	"path/filepath"
	"strings"
	"vov.cx/kagura/utils/app"
	"vov.cx/kagura/utils/exec"
	"vov.cx/kagura/utils/gobuild"
)

func init() {
	root.AddCommand(
		app.New(app.Use("gorun", "gor"), b.BuildFlagOption(), goBuildRun(b, "run"), app.Comment("go run")),
		app.New(app.Use("gobuild", "gob"), b.BuildFlagOption(), goBuildRun(b, "build"), app.Comment("go build")),
		app.New(app.Use("gomod", "gom"), app.SubCommand(modTidy(), modDownload()), app.Comment("go mod")),

		app.New(
			app.Use("go"),
			app.Comment("go wrapper, go run/build/mod"),
			app.SubCommand(
				app.New(app.Use("run"), b.BuildFlagOption(), goBuildRun(b, "run"), app.Comment("go run")),
				app.New(app.Use("build"), b.BuildFlagOption(), goBuildRun(b, "build"), app.Comment("go build")),
				app.New(app.Use("mod"), app.SubCommand(modTidy(), modDownload()), app.Comment("go mod")),
			),
		),
	)
}

func goBuildRun(b *gobuild.Builder, command string) app.ApplyOption {
	return app.Run(func(c *app.Command, args []string) {
		b.Files = args
		app.CheckExit(b.BuildCommand(command).Run(c.Context()))
		if b.UpxPack && command == "build" {
			app.CheckExit(b.Upx().Run(c.Context()))
		}
	})
}

func modTidy() *app.Command {
	var (
		e bool
		v bool
	)

	return app.New(
		app.Use("tidy [-e] [-v]"),
		app.Flags(func(fs *app.FlagSet) {
			fs.BoolVarP(&e, "error-continue", "e", e, "causes tidy to attempt to proceed despite errors encountered while loading packages.")
			fs.BoolVarP(&v, "verbose", "v", v, "causes tidy to print information about removed modules to standard error.")
		}),

		app.Run(func(c *app.Command, files []string) {
			var dir string
			if len(files) > 0 {
				dir = filepath.ToSlash(files[0])
				if strings.HasSuffix(dir, "/go.mod") {
					dir = filepath.Dir(filepath.FromSlash(dir))
				}
				dir = filepath.FromSlash(dir)
			}

			args := []string{"mod", "tidy"}
			if errorContinue, _ := c.Flags().GetBool("error-continue"); errorContinue {
				args = append(args, "-e")
			}

			if verbose, _ := c.Flags().GetBool("verbose"); verbose {
				args = append(args, "-v")
			}

			app.CheckExit(exec.Go(args...).SetDir(dir).Run(c.Context()))
		}),
	)
}

func modDownload() *app.Command {
	var (
		j bool
		x bool
	)

	return app.New(
		app.Use("download [-x] [--json] [modules]"),
		app.Flags(func(fs *app.FlagSet) {
			fs.BoolVar(&j, "json", j, `The --json flag causes download to print a sequence of JSON objects
to standard output, describing each downloaded module (or failure),
corresponding to this Go struct:

    type Module struct {
        Path     string // module path
        Version  string // module version
        Error    string // error loading module
        Info     string // absolute path to cached .info file
        GoMod    string // absolute path to cached .mod file
        Zip      string // absolute path to cached .zip file
        Dir      string // absolute path to cached source root directory
        Sum      string // checksum for path, version (as in go.sum)
        GoModSum string // checksum for go.mod (as in go.sum)
    }
`)
			fs.BoolVarP(&x, "x", "x", x, "causes download to print the commands download executes.")
		}),

		app.Comment("downloads the named modules", `downloads the named modules, which can be module patterns selecting
dependencies of the main module or module queries of the form path@version.
With no arguments, download applies to all dependencies of the main module
(equivalent to 'go mod download all').

The go command will automatically download modules as needed during ordinary
execution. The "go mod download" command is useful mainly for pre-filling
the local cache or to compute the answers for a Go module proxy.

By default, download writes nothing to standard output. It may print progress
messages and errors to standard error.
`),

		app.Run(func(c *app.Command, modules []string) {
			args := []string{"mod", "download"}
			if j {
				args = append(args, "-json")
			}
			if x {
				args = append(args, "-x")
			}

			args = append(args, modules...)

			app.CheckExit(exec.Go(args...).Run(c.Context()))
		}),
	)
}
